//- Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
//- 
//- Licensed under the Apache License, Version 2.0 (the "License");
//- you may not use this file except in compliance with the License.
//- You may obtain a copy of the License at
//- 
//-     http://www.apache.org/licenses/LICENSE-2.0
//- 
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.

extends layout

block content
  h1 My Wishlist
  .wishlist-container
    if wishlistItems && wishlistItems.length
      each product in wishlistItems
        .wishlist-item(id=`wishlist_item_${product.id}`)
          img.wishlist-image(src=product.image)
          .wishlist-name= product.name
          .wishlist-price= `$${product.price}`
          button.remove-from-wishlist(data-product-id=product.id) Remove
    else
      .empty-wishlist
        h2 Your wishlist is empty

  link(rel="stylesheet", href="/css/wishlist.css")
  script.
    const wishlistContainer = document.querySelector('.wishlist-container')

    wishlistContainer.addEventListener('click', async (e) => {
      if (e.target.classList.contains('remove-from-wishlist')) {
        const productId = e.target.dataset.productId
        const res = await fetch('/api/wishlist/remove', {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            productId
          })
        })

        const data = await res.json()
        if (data.success) {
          const item = document.querySelector(`#wishlist_item_${productId}`)
          item.remove()

          if (!document.querySelector('.wishlist-item')) {
            location.reload()
          }
        }
      }
    })